package com.zr.daoimpl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.zr.dao.TreeDao;
import com.zr.model.Cfunction;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

@Repository("treeDao")
public class TreeDaoImpl<T> extends BaseDaoImpl<T>implements TreeDao<T>{

	@Override
	public JSONArray getAllFunctionsBypid(int pid, String fid) {
	   String hql="from Cfunction where pid=:pid and fid in("+fid+")";
	   Query que=this.getCurrentSession().createQuery(hql);
	     que.setInteger("pid", pid);
	     List<Cfunction> functions=que.list();
	     JSONArray functions1=new JSONArray();
	     for (Cfunction function : functions) {
	    	 JSONObject func=new JSONObject();
	    	  func.put("id",function.getFid());
	    	  func.put("text", function.getFname());
	    	  func.put("state",function.getState());
	    	  JSONObject  attr=new JSONObject();
				attr.put("furl",function.getUrl());
				func.put("attributes", attr);
				  functions1.add(func);
		}
		return functions1;
		
	}

	@Override
	public JSONArray getCurrentFunctionBypid(int pid, String fid) {
		 JSONArray functions=this.getAllFunctionsBypid(pid, fid);
		 for (int i = 0; i < functions.size(); i++) {
			String s=functions.getJSONObject(i).getString("state");
			if("open".equals(s)){
				continue;
			}else{
				int id=functions.getJSONObject(i).getInt("id");
				   JSONArray fun=this.getCurrentFunctionBypid(id, fid);
				   functions.getJSONObject(i).put("children",fun);
			}
		}
		
		return functions;
	}

	@Override
	public String getpidByuid(int uid) {
		String hql="select u.crole.fids from Cuser as u where u.uid=:uid";
		Query que=this.getCurrentSession().createQuery(hql);
		que.setInteger("uid", uid);
		String s=(String)que.uniqueResult();
		 return s;
	}

}
